﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using CUWo.App.CustomControl;
using CUWo.App.Resources;
using CUWo.Common;
using CUWo.Common.Entities;
using CUWo.Common.Entities.WoInterface.HttpJsonResult;
using CUWo.Common.WebHelper;
using CUWo.Common.WoInterfaceCommunication;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace CUWo.App.WoControls
{
    public partial class WoUserCenterRegister : UserControl
    {
        public WoUserCenterRegister()
        {
            InitializeComponent();
        }

        #region 输入控件事件
        private void txtMobile_GotFocus(object sender, RoutedEventArgs e)
        {
            if (this.txtMobile.Text.Equals(AppResources.UserCenterRegisterInputChinaUnicomMobile))
            {
                this.txtMobile.Text = string.Empty;
            }
        }

        private void txtMobile_LostFocus(object sender, RoutedEventArgs e)
        {
            string mobile = this.txtMobile.Text.Trim();
            if (string.IsNullOrWhiteSpace(mobile))
            {
                this.txtMobile.Text = AppResources.UserCenterRegisterInputChinaUnicomMobile;
            }
            else
            {
                if (Helper.IsChinaUnicomMobile(this.txtMobile.Text.Trim()))
                {
                    this.pwdNewPassword.Focus();
                }
            }
        }

        private void pwdNewPassword_LostFocus(object sender, RoutedEventArgs e)
        {
            string password = this.pwdNewPassword.Password.Trim();
            if (string.IsNullOrWhiteSpace(password))
            {
                this.txtNewPassword.Visibility = System.Windows.Visibility.Visible;
                this.pwdNewPassword.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void txtNewPassword_GotFocus(object sender, RoutedEventArgs e)
        {
            this.txtNewPassword.Visibility = System.Windows.Visibility.Collapsed;
            this.pwdNewPassword.Visibility = System.Windows.Visibility.Visible;
            this.pwdNewPassword.Focus();
        }

        private void pwdConfirmNewPassword_LostFocus(object sender, RoutedEventArgs e)
        {
            string password = this.pwdConfirmNewPassword.Password.Trim();
            if (string.IsNullOrWhiteSpace(password))
            {
                this.txtConfirmNewPassword.Visibility = System.Windows.Visibility.Visible;
                this.pwdConfirmNewPassword.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void txtConfirmNewPassword_GotFocus(object sender, RoutedEventArgs e)
        {
            this.txtConfirmNewPassword.Visibility = System.Windows.Visibility.Collapsed;
            this.pwdConfirmNewPassword.Visibility = System.Windows.Visibility.Visible;
            this.pwdConfirmNewPassword.Focus();
        }
        #endregion 输入控件事件


        /// <summary>
        /// 手机号码注册
        /// </summary>
        public void MobileRegister()
        {
            //获取用户手机号
            string mobileNumber = this.txtMobile.Text.Trim();
            string password = this.pwdNewPassword.Password.Trim();
            string confirmPassword = this.pwdConfirmNewPassword.Password.Trim();
            if (string.IsNullOrWhiteSpace(mobileNumber))
            {
                MessageToastManager.Show(AppResources.UserCenterRegisterInputChinaUnicomMobile);
                return;
            }
            if (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(confirmPassword))
            {
                MessageToastManager.Show(AppResources.UserCenterRegisterInputPassword);
                return;
            }
            if (!password.Equals(confirmPassword))
            {
                MessageToastManager.Show("两次密码输入不一致！");
                return;
            }

            //获取请求地址
            string requestUrl = new CUWo.Common.WoInterfaceCommunication.MobileRegister().GetUrl(mobileNumber, password);
            LogHelper.LogInfo(requestUrl);
            //

            PopupProgressBar.OpenProgressBar();
            Stopwatch sw = new Stopwatch();
            sw.Start();
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);
                        LogHelper.LogInfo("耗时：" + sw.Elapsed.ToString());
                        PopupProgressBar.CloseProgressBar();

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        JsonResultRootJsonCharacterString rootCharacterString = JSONHelper.Deserialize<JsonResultRootJsonCharacterString>(result);
                        if (rootCharacterString == null)
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            AESHelper aesHelper = new AESHelper(AESHelper.KeySize.Bits128, AESHelper.Hex2Byte(new CommunicationBase().CHANNEL_PASSWORD));
                            byte[] decryptByteResult = aesHelper.InvCipher(AESHelper.Hex2Byte(rootCharacterString.RootValue));
                            string decryptStringResult = Encoding.UTF8.GetString(decryptByteResult, 0, decryptByteResult.Length);
                            LogHelper.LogInfo("Decrypt:\t" + decryptStringResult);
                            JsonResultRootMsgCharacterString rootMessage = JSONHelper.Deserialize<JsonResultRootMsgCharacterString>(decryptStringResult);
                            if (rootMessage != null && rootMessage.Message != null)
                            {
                                if (rootMessage.Message.MessageErrors != null && rootMessage.Message.MessageErrors.Count > 0)
                                {
                                    MessageToastManager.Show(rootMessage.Message.MessageErrors[0].MessageContent, MessageToastLevel.Error);
                                    //有错误
                                }
                                else if (rootMessage.Message.MessageWarns != null && rootMessage.Message.MessageWarns.Count > 0)
                                {
                                    MessageToastManager.Show(rootMessage.Message.MessageWarns[0].MessageContent, MessageToastLevel.Warn);
                                }
                                else
                                {
                                    //成功
                                    if (rootMessage.Message.MessagePrompts != null && rootMessage.Message.MessagePrompts.Count > 0)
                                    {
                                        MessageToastManager.Show(rootMessage.Message.MessagePrompts[0].MessageContent, MessageToastLevel.Info);
                                        //OperationStatus status = RomHelper.UpdateRom(mobileNumber, password);
                                        RomInfo romInfo = new RomInfo() { Mobile = mobileNumber, Password = password, IsPush = true };
                                        OperationStatus status = RomHelper.UpdateRom(romInfo);
                                        MessageToastManager.Show(status.Message, status.Status ? MessageToastLevel.Info : MessageToastLevel.Error);
                                    }
                                }
                            }
                        }
                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {
                    PopupProgressBar.CloseProgressBar();
                    MessageToastManager.Show(err.Message);
                }
            }, webTask);
        }

    }
}
